package com.milkshopbackend.milkshop.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {
    private final RedisTemplate<String, Object> redisTemplate;

    public RedisLockUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 加锁
     * @param key 锁的key
     * @param expireSec 过期时间（秒）
     * @return 唯一标识（解锁时用）
     */
    public String lock(String key, long expireSec) {
        String uuid = UUID.randomUUID().toString();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, uuid, expireSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success) ? uuid : null;
    }

    /**
     * 解锁
     * @param key 锁的key
     * @param uuid 加锁时返回的唯一标识
     */
    public void unlock(String key, String uuid) {
        Object val = redisTemplate.opsForValue().get(key);
        if (uuid.equals(val)) {
            redisTemplate.delete(key);
        }
    }
} 